<script lang="ts" setup>
import type {
  OnActionClickParams,
  VxeTableGridOptions,
} from '#/adapter/vxe-table';
import type { RoutingStepModel, StepTaskModel } from '#/api/process/models';

import { reactive, ref } from 'vue';

import { Page, useVbenDrawer, useVbenModal } from '@vben/common-ui';

import { Button, message, Space } from 'ant-design-vue';

import { useVbenVxeGrid } from '#/adapter/vxe-table';
import {
  deleteStepTaskApi,
  getStepTaskListApi,
  reorganizeStepTaskSeqAsyncApi,
} from '#/api/process/stepTask';
import { $t } from '#/locales';

import RoutingStep2 from '../routing-step/index.vue';
import RoutingStepStandardFormDrawer from '../step-standard/modules/form-drawer.vue';
import { useColumns } from './data';
import StepTaskCopyFormModal from './modules/copy-form-modal.vue';
import StepTaskFormModal from './modules/form-modal.vue';

const stepId = ref(0);
const state = reactive({
  opName: '',
});

const [FormModal, formModalApi] = useVbenModal({
  connectedComponent: StepTaskFormModal,
  destroyOnClose: true,
});

const [StandardFormDrawer, standardFormDrawerApi] = useVbenDrawer({
  connectedComponent: RoutingStepStandardFormDrawer,
  destroyOnClose: true,
});

const [CopyFormModal, formCopyModalApi] = useVbenModal({
  connectedComponent: StepTaskCopyFormModal,
  destroyOnClose: true,
});

/**
 * 创建
 */
function onCreate() {
  formModalApi
    .setData({
      stepId: stepId.value,
    })
    .open();
}

/**
 * 编辑
 * @param row
 */
function onOpen(row: StepTaskModel) {
  standardFormDrawerApi
    .setData({
      stepId: stepId.value,
      stepTaskId: row.id,
      opName: state.opName,
      taskName: row.taskName,
    })
    .open();
}

/**
 * 编辑
 * @param row
 */
function onCopy(row: StepTaskModel) {
  formCopyModalApi.setData(row).open();
}

/**
 * 编辑
 * @param row
 */
function onEdit(row: StepTaskModel) {
  formModalApi
    .setData({
      values: row,
      stepId: stepId.value,
    })
    .open();
}

/**
 * 删除
 * @param row
 */
function onDelete(row: StepTaskModel) {
  const hideLoading = message.loading({
    content: $t('ui.actionMessage.deleting', [row.taskName]),
    duration: 0,
    key: 'action_process_msg',
  });
  deleteStepTaskApi(row.id)
    .then(() => {
      message.success({
        content: $t('ui.actionMessage.deleteSuccess', [row.taskName]),
        key: 'action_process_msg',
      });
      loadData();
    })
    .catch(() => {
      hideLoading();
    });
}

/**
 * 表格操作按钮的回调函数
 */
function onActionClick({ code, row }: OnActionClickParams<StepTaskModel>) {
  switch (code) {
    case 'copy': {
      onCopy(row);
      break;
    }
    case 'delete': {
      onDelete(row);
      break;
    }
    case 'edit': {
      onEdit(row);
      break;
    }
    case 'open': {
      onOpen(row);
      break;
    }
  }
}

const [Grid, gridApi] = useVbenVxeGrid({
  gridOptions: {
    columns: useColumns(onActionClick),
    data: [],
    border: true,
    stripe: true,
    pagerConfig: {
      enabled: false,
    },
  } as VxeTableGridOptions,
});

/**
 * 重组顺序号
 */
async function reorganizeSeq() {
  gridApi.setLoading(true);
  await reorganizeStepTaskSeqAsyncApi(stepId.value);
  loadData();
  gridApi.setLoading(false);
}

/**
 * 加载数据
 */
function loadData() {
  if (stepId.value) {
    getStepTaskListApi(stepId.value).then((data) => {
      gridApi.grid.loadData(data);
    });
  } else {
    gridApi.grid.loadData([]);
  }
}

/**
 * 点击后选择行
 */
function itemSelected(item?: RoutingStepModel) {
  gridApi.setLoading(true);
  stepId.value = item?.id ?? 0;
  state.opName = item?.operation.opName ?? '';
  loadData();
  gridApi.setLoading(false);
}
</script>

<template>
  <Page auto-content-height>
    <div class="flex h-full w-full">
      <div class="h-full w-4/12">
        <RoutingStep2 @item-selected="itemSelected" />
      </div>
      <div class="ml-2 h-full w-8/12">
        <Grid>
          <template #toolbar-actions>
            <Space>
              <Button :disabled="!stepId" type="primary" @click="onCreate()">
                新增工步
              </Button>
              <Button
                :disabled="!stepId"
                type="primary"
                @click="reorganizeSeq()"
              >
                重组顺序号
              </Button>
            </Space>
          </template>
        </Grid>
      </div>
    </div>
    <StandardFormDrawer class="w-9/12" />
    <FormModal @success="() => loadData()" />
    <CopyFormModal @success="() => loadData()" />
  </Page>
</template>
